package chenji.yourticket.press;

import java.util.HashMap;

import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

import chenji.yourticket.Main;
import chenji.yourticket.model.ModelInfo;

public class PressManager {
	private final HashMap<Player, PressInventory> miao = new HashMap<Player, PressInventory>();

	public void openInventory(Player p, ModelInfo model) {
		this.miao.put(p, new PressInventory(p, model));
	}

	public void clickInventory(int slot, Player p) {
		if (this.miao.containsKey(p)) {
			PressInventory i = miao.get(p);
			i.clickInventory(slot);
		}
	}

	public int getMaxAmount(Player p, ModelInfo modelinfo) {
		double prePrice = Main.getVIPDiscountManager().getDiscount(p) * Main.getMaterialManager().getPrice(modelinfo.getItem().getType());
		double balance = Main.getEconomy().getBalance(p);
		if (balance == 0.0) {
			return 0;
		}
		int amount = (int) (balance / prePrice);
		int freesize = this.getFreeSize(p);
		if (amount < freesize) {
			return amount;
		}
		return freesize;
	}

	public int getFreeSize(Player p) {
		int i = 0;
		for (ItemStack item : p.getInventory().getContents()) {
			if (this.isNull(item)) {
				i++;
			}
		}
		if (this.isNull(p.getInventory().getBoots())) {
			i--;
		}

		if (this.isNull(p.getInventory().getChestplate())) {
			i--;
		}
		if (this.isNull(p.getInventory().getHelmet())) {
			i--;
		}
		if (this.isNull(p.getInventory().getLeggings())) {
			i--;
		}
		return i * 64;
	}

	private boolean isNull(ItemStack i) {
		if (i == null) {
			return true;
		}
		if (i.getType().equals(Material.AIR)) {
			return true;
		}
		return false;
	}

	public void unload() {
		for (Player p : this.miao.keySet()) {
			p.closeInventory();
		}
	}

}
